package com.tmsps.ne4Weixin.api;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.tmsps.ne4Weixin.beans.OAuthToken;
import com.tmsps.ne4Weixin.beans.UserInfo;
import com.tmsps.ne4Weixin.config.WxConfig;
import com.tmsps.ne4Weixin.utils.HttpClient;

public class OAuthAPI extends BaseAPI {

	public static final String SNSAPI_BASE = "snsapi_base";
	public static final String SNSAPI_USERINFO = "snsapi_userinfo";

	public OAuthAPI(WxConfig config) {
		super(config);
	}
	/**
	 * @author zhangwei 396033084@qq.com 
	 * @param backUrl 回调地址
	 * @param scope 获取用户信息方式
	 * @param state 回调地址跟随参数
	 * @return 请求地址
	 */
	public String getOAuthUrl(String backUrl, String scope, String state) {
		String userState = StringUtils.isEmpty(state) ? "STATE" : state;
		try {
			StringBuilder SB = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?");
			String url = URLEncoder.encode(backUrl, "UTF-8");
			SB.append("appid=").append(this.config.getAppid()).append("&redirect_uri=").append(url).append("&response_type=code&scope=").append(scope).append("&state=").append(userState).append("#wechat_redirect");
			return SB.toString();
		} catch (UnsupportedEncodingException e) {
			log.error(e.toString());
			return "";
		}
	}
	
	final String tokenUrl = BaseURL.concat("/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code");
	// 从回调地址获取code参数，获取token信息
	public OAuthToken getToken(String code) {
		String url = String.format(tokenUrl, config.getAppid(), config.getSecret(), code);
		String result = HttpClient.httpGet(url, null);
		return JSONObject.parseObject(result, OAuthToken.class);
	}
	
	final String getUserInfoUrl = BaseURL.concat("/sns/userinfo?access_token=%s&openid=%s&lang=%s");
	//拉取用户信息
	public UserInfo getUserInfo(String token, String openId) {
		String url = String.format(getUserInfoUrl, token, openId, "zh_CN");
		String result = HttpClient.httpGet(url, null);
		return JSONObject.parseObject(result, UserInfo.class);
	}
	//拉取用户信息
	public UserInfo getUserInfo(OAuthToken token){
		String url = String.format(getUserInfoUrl, token.getAccess_token(), token.getOpenid(), "zh_CN");
		String result = HttpClient.httpGet(url, null);
		return JSONObject.parseObject(result, UserInfo.class);
	}
	
	// 获取当前地址的完整url,包含参数
	public static String getRefererUrl(HttpServletRequest request) {
		String url = request.getRequestURL().toString();
		StringBuilder params = new StringBuilder();
		@SuppressWarnings("unchecked")
		Enumeration<String> pnames = request.getParameterNames();
		while (pnames.hasMoreElements()) {
			String p = pnames.nextElement();
			String val = request.getParameter(p);
			params.append(String.format("&%s=%s", p, val));
		}
		if (params.length() > 0) {
			url += "?" + params.substring(1);
		}
		return url;
	}
}
